//
//  ChatSelectAddressViewController.m
//  Btpin
//
//  Created by Vic on 2019/4/25.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "ChatSelectAddressViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <BMKLocationKit/BMKLocationManager.h>
#import "LYChatSelectAddressCell.h"

@interface ChatSelectAddressViewController ()<BMKMapViewDelegate,BMKLocationManagerDelegate,BMKGeoCodeSearchDelegate,UITableViewDataSource,UITableViewDelegate>

//显示地图
@property (nonatomic, strong) BMKMapView *mapView;
//定位
@property (nonatomic, strong) BMKLocationManager *locationManager;
//大头针
@property(nonatomic , strong) BMKPointAnnotation *annotation;
//逆地理编码检索对象
@property(nonatomic , strong) BMKGeoCodeSearch *search;

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger selectIndex;

@end

@implementation ChatSelectAddressViewController

-(BMKMapView *)mapView{
    if (!_mapView){
        _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0,0, WIDTH , HEIGHT- HeightOfStatusBarAndNavigationBar-kAdaptScreen(300.0))];
        _mapView.delegate = self;
        _mapView.showMapScaleBar = YES;
        _mapView.showsUserLocation = YES;
        _mapView.zoomLevel = 14;
    }
    return _mapView;
}

-(BMKLocationManager *)locationManager{
    if (!_locationManager){
        _locationManager = [[BMKLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
        _locationManager.distanceFilter = kCLLocationAccuracyBestForNavigation;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        _locationManager.pausesLocationUpdatesAutomatically = NO;
        // YES的话是可以进行后台定位的，但需要项目配置，否则会报错，具体参考开发文档
        _locationManager.allowsBackgroundLocationUpdates = NO;
        _locationManager.locationTimeout = 10;
        _locationManager.reGeocodeTimeout = 10;
    }
    return _locationManager;
}

-(BMKGeoCodeSearch *)search{
    if (!_search){
        _search = [[BMKGeoCodeSearch alloc] init];
        _search.delegate = self;
    }
    return _search;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"当前位置";
    [self.view addSubview:self.mapView];
    self.selectIndex = 0;
    [self creareSubview];
    //开启定位
    [self.locationManager startUpdatingLocation];
    [self creareSubview];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
}

- (void)creareSubview{
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, _mapView.bottom, WIDTH,kAdaptScreen(300.0)) style:UITableViewStyleGrouped];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.bounces = NO;
    self.tableview.showsVerticalScrollIndicator = NO;
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableview.backgroundColor = RGB(247, 247, 247);
    self.tableview.sectionIndexBackgroundColor = [UIColor clearColor];
    [self.tableview registerClass:[LYChatSelectAddressCell class] forCellReuseIdentifier:kCellIdentifier_LYChatSelectAddressCell];
    [self.view addSubview:self.tableview];
    
    UIButton *sendbtn = [UIToolsControl initButtonWithFrame:CGRectMake(0, 0, 60, 40) imageName:nil target:self action:@selector(sendBtnClick:) title:@"发送" titleColor:THEMECOLOR_OF_ORANGE];
    sendbtn.titleLabel.font = Font(Font_15);
    UIBarButtonItem *sendItem= [[UIBarButtonItem alloc] initWithCustomView:sendbtn];
    self.navigationItem.rightBarButtonItem = sendItem;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LYChatSelectAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_LYChatSelectAddressCell forIndexPath:indexPath];
    BMKPoiInfo *POIInfo = self.dataArray[indexPath.row];
    [cell setTitle:POIInfo.name detail:POIInfo.address isSelect:(indexPath.row == self.selectIndex)? YES:NO];
    return cell;
}

#pragma mark -- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row != self.selectIndex) {
        self.selectIndex = indexPath.row;
        [tableView reloadData];
        BMKPoiInfo *POIInfo = self.dataArray[indexPath.row];
        if (self.annotation){
            //若存在大头针 则先删除
            [self.mapView removeAnnotation:self.annotation];
        }
        self.annotation = [[BMKPointAnnotation alloc]init];
        self.annotation.coordinate = POIInfo.pt;
        [self.mapView addAnnotation:self.annotation];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001f;
}

#pragma mark - 定位至当前位置 - BMKLocationManagerDelegate
- (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager didUpdateLocation:(BMKLocation * _Nullable)locatio orError:(NSError * _Nullable)error{
    if (locatio){
        //显示当前位置
        BMKUserLocation * loca = [[BMKUserLocation alloc] init];
        loca.location = locatio.location;
        [self.mapView updateLocationData:loca];
//        [self.mapView setCenterCoordinate:locatio.location.coordinate animated:YES];
        
        CGFloat locaLatitude = locatio.location.coordinate.latitude;//纬度
        CGFloat locaLongitude =locatio.location.coordinate.longitude;//精度
        //反地理编码出地理位置
        CLLocationCoordinate2D pt=(CLLocationCoordinate2D){0,0};
        pt=(CLLocationCoordinate2D){locaLatitude,locaLongitude};
        
        //构造逆地理编码检索参数
        BMKReverseGeoCodeSearchOption *reverseGeoCodeOption = [[BMKReverseGeoCodeSearchOption alloc]init];
        reverseGeoCodeOption.location = pt;
        // 是否访问最新版行政区划数据（仅对中国数据生效）
        reverseGeoCodeOption.isLatestAdmin = YES;
        //发起逆地理编码检索请求
        BOOL flag = [self.search reverseGeoCode: reverseGeoCodeOption];
        if (flag){
            NSLog(@"逆geo检索发送成功");
        }else{
            NSLog(@"逆geo检索发送失败");
        }
        [self.locationManager stopUpdatingHeading];
    }
}

#pragma mark - 地图点击事件
-(void)mapView:(BMKMapView *)mapView  onClickedMapBlank:(CLLocationCoordinate2D)coordinate{
    if (self.annotation){
        //若存在大头针 则先删除
        [self.mapView removeAnnotation:self.annotation];
    }
    self.annotation = [[BMKPointAnnotation alloc]init];
    self.annotation.coordinate = coordinate;
    [self.mapView addAnnotation:self.annotation];
    [self.mapView setCenterCoordinate:coordinate animated:YES];
    
    //构造逆地理编码检索参数
    BMKReverseGeoCodeSearchOption *reverseGeoCodeOption = [[BMKReverseGeoCodeSearchOption alloc]init];
    reverseGeoCodeOption.location = coordinate;
    // 是否访问最新版行政区划数据（仅对中国数据生效）
    reverseGeoCodeOption.isLatestAdmin = YES;
    //发起逆地理编码检索请求
    BOOL flag = [self.search reverseGeoCode: reverseGeoCodeOption];
    if (flag){
        NSLog(@"逆geo检索发送成功");
    }else{
        NSLog(@"逆geo检索发送失败");
    }
}

- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR){
        //在此处理正常结果
        self.dataArray = [NSMutableArray arrayWithArray:result.poiList];
        [self.tableview reloadData];
        BMKPoiInfo *POIInfo = result.poiList[0];
        BMKSearchRGCRegionInfo *regionInfo = [[BMKSearchRGCRegionInfo alloc] init];
        if (result.poiRegions.count > 0){
            regionInfo = result.poiRegions[0];
        }
        //反地理编码得到的位置信息，自选
        NSString *message = [NSString stringWithFormat:@"经度：%f\n纬度：%f\n地址名称：%@\n商圈名称：%@\n可信度：%ld\n国家名称：%@\n省份名称：%@\n城市名称：%@\n区县名称：%@\n乡镇：%@\n街道名称：%@\n街道号码：%@\n行政区域编码：%@\n国家代码：%@\n方向：%@\n距离：%@\nPOI名称：%@\nPOI经纬坐标：%f\nPOI纬度坐标：%f\nPOI地址信息：%@\nPOI电话号码：%@\nPOI的唯一标识符：%@\nPOI所在省份：%@\nPOI所在城市：%@\nPOI所在行政区域：%@\n街景ID：%@\n是否有详情信息：%d\nPOI方向：%@\nPOI距离：%ld\nPOI邮编：%ld\n相对位置关系：%@\n归属区域面名称：%@\n归属区域面类型：%@\n语义化结果描述：%@",
                             result.location.longitude,
                             result.location.latitude,
                             result.address,
                             result.businessCircle,
                             (long)result.confidence,
                             result.addressDetail.country,
                             result.addressDetail.province,
                             result.addressDetail.city,
                             result.addressDetail.district,
                             result.addressDetail.town,
                             result.addressDetail.streetName,
                             result.addressDetail.streetNumber,
                             result.addressDetail.adCode,
                             result.addressDetail.countryCode,
                             result.addressDetail.direction,
                             result.addressDetail.distance,
                             POIInfo.name,
                             POIInfo.pt.longitude,
                             POIInfo.pt.latitude,
                             POIInfo.address,
                             POIInfo.phone,
                             POIInfo.UID,
                             POIInfo.province,
                             POIInfo.city,
                             POIInfo.area,
                             POIInfo.streetID, POIInfo.hasDetailInfo, POIInfo.direction, (long)POIInfo.distance, (long)POIInfo.zipCode, regionInfo.regionDescription, regionInfo.regionName, regionInfo.regionTag, result.sematicDescription];
        
        NSLog(@"--->%@",message);
        self.annotation.title = result.sematicDescription;
    }else{
        NSLog(@"检索失败");
    }
}

#pragma mark -- Acion
- (void)sendBtnClick:(UIButton *)button{
    if (self.dataArray.count) {
        BMKPoiInfo *POIInfo = self.dataArray[self.selectIndex];
        //block返回字典数据 desc：地点地址；latitude：纬度；longitude：经度
        NSString *desc = POIInfo.address.length ? POIInfo.address :@"";
        CGFloat latitude = POIInfo.pt.latitude;
        CGFloat longitude = POIInfo.pt.longitude;
        NSDictionary *dic = @{
                              @"desc":desc,
                              @"latitude":[NSNumber numberWithFloat:latitude],
                              @"longitude":[NSNumber numberWithFloat:longitude]
                              };
        _select(dic);
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        SVPHUDError(@"定位失败");
    }
}




//- (void)viewDidLoad {
//    [super viewDidLoad];
//    [self initUI];
//}
//- (void)initUI {
//
////    _locationManager = [[CLLocationManager alloc] init];
////    [_locationManager requestWhenInUseAuthorization];
////    _locationManager.delegate = self;
////    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
////    _locationManager.distanceFilter = kCLDistanceFilterNone;
////    // 开始定位
////    [_locationManager startUpdatingLocation];//开始定位之后会不断的执行代理方法更新位置会比较费电所以建议获取完位置即时关闭更新位置服务
////    //初始化地理编码器
////    _geocoder = [[CLGeocoder alloc] init];
//}
//- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
//    [_locationManager stopUpdatingLocation]; //不用的时候关闭更新位置服务
//    locationRecard = locations.lastObject;
//    __weak __typeof(self)weakSelf = self;
//    [_geocoder reverseGeocodeLocation:locationRecard completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//        if (placemarks.count > 0) {
//            CLPlacemark *placemark = [placemarks objectAtIndex:0];
//            NSLog(@"%@",placemark.name);
//            //获取城市
//            NSString *city = placemark.locality;
//            if (!city) { //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
//                city = placemark.administrativeArea;
//            }
//            NSString *address = [NSString stringWithFormat:@"%@%@%@", city, placemark.subLocality, placemark.thoroughfare];
//            NSDictionary *dic = @{@"desc":address, @"latitude":[NSNumber numberWithDouble:self->locationRecard.coordinate.latitude], @"longitude":[NSNumber numberWithDouble:self->locationRecard.coordinate.longitude]};
//            __strong __typeof(weakSelf)strongSelf = weakSelf;
////            [strongSelf.chat sendWeizhi:dic];
//        } else if (error == nil && [placemarks count] == 0) {
//            NSLog(@"No results were returned.");
//        } else if (error != nil) {
//            NSLog(@"An error occurred = %@", error);
//        }
//    }];
//}

@end
